<template>
  <div>
    <el-select size="small" popper-class="singleSelectGroup" :clearable="clearable" :multiple="multiple" v-model="defaultValue" @change="handleChange($event)">
      <el-option-group v-for="group in groupSelectOptions" :key="group.label" :label="group.label">
        <el-option
          v-if="defaultValue"
          :disabled="defaultValue.indexOf(item.value) !== -1"
          v-for="item in group.children"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-option-group>
    </el-select>
  </div>
</template>

<script>
export default {
  props: {
    clearable: {
      type: Boolean,
      default: true
    },
    multiple: {
      type: Boolean,
      default: true
    },
    modelValue: {
      type: Array,
      default: []
    },
    groupData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      defaultValue: [],
      currentId: null, //当前选中元素
      groupSelectOptions: []
    };
  },
  watch: {
    groupData: {
      handler(value) {
        this.groupSelectOptions = structuredClone(value);
      },
      immediate: true,
      deep: true
    },
    modelValue: {
      handler(value) {
        if (value) {
          this.defaultValue = structuredClone(value);
        }
      }
    }
  },
  methods: {
    handleChange(obj) {
      this.currentId = obj[obj.length - 1]; //获取当前选中的值
      if (this.currentId) {
        if (this.defaultValue.length > 0) {
          let index = this.defaultValue.indexOf(this.currentId); //获取当前点击项在选择项中的第几个
          if (index > -1) {
            // 查找当前选项的父对象
            let parentObj = this.groupSelectOptions.find((item) => {
              let child = item.children.filter((child) => child.value === this.currentId);
              if (child.length) {
                return item;
              }
              return null;
            });
            // 根据当前对象的父级筛选出所有的兄弟元素
            parentObj &&
              parentObj.children.forEach((item) => {
                let idx = this.defaultValue.indexOf(item.value);
                if (idx >= 0 && item.value !== this.currentId) {
                  this.defaultValue.splice(idx, 1);
                }
              });
          }
        }
      }
      this.$emit('selected', this.defaultValue);
      this.currentId = null;
    }
  }
};
</script>

<style scoped lang="scss">
.singleSelectGroup {
  .el-select-group .el-select-dropdown__item.selected.is-disabled {
    color: #409eff !important;
  }
}
</style>
